package com.zhangwei.xutils.utils;

import android.app.Activity;
import android.content.Context;
import android.view.View;

import com.zhangwei.xutils.annotation.ResById;
import com.zhangwei.xutils.annotation.ResType;
import com.zhangwei.xutils.annotation.ViewById;

import java.lang.reflect.Field;

/**
 * @author zhangwei
 * @version V1.0
 * @Title: Advanced
 * @Package com.zhangwei.xutils.utils
 * @Description:
 * @date 15/10/19 下午3:33
 *
 * 初始化Activity的View
 */

public class ViewUtils1 {

    /**
     * 初始化Activity所有View,资源文件
     *
     * 反射  + 注解
     *
     * @param activity
     */
    public static void initView(Activity activity) {
        //第一步获得这个类的Class
        //第二步获得这个类的所有属性
        //第三步给属性赋值
        Class<?> cls = activity.getClass();
        Field[] fields = cls.getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field != null) {
                    ViewById viewAnno = field.getAnnotation(ViewById.class);
                    if (viewAnno != null) {
                        int id = viewAnno.id();
                        View view = activity.findViewById(id);
                        if (view != null) {
                            try {
                                field.setAccessible(true);
                                field.set(activity, view);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    else {
                        ResById resAnno = field.getAnnotation(ResById.class);
                        if (resAnno != null) {
                            int id = resAnno.id();
                            ResType type = resAnno.type();
                            Object value = getRes(activity, type, id);
                            if (value != null) {
                                try {
                                    field.setAccessible(true);
                                    field.set(activity, value);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }


            }
        }


    }


    public static Object getRes(Context context, ResType type, int id) {

        Object vaule = null;

        switch (type) {
            case String:
                vaule = context.getResources().getString(id);
                break;
            case Drawable:
                vaule = context.getResources().getDrawable(id);
                break;
            case Color:
                vaule = context.getResources().getColor(id);
                break;

        }
        return vaule;

    }


}
